﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM.Business.DataCenter
{
    public partial class VSMItemMasterData : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    if (dbType != "VSM")
                    {
                        this.grvWH.Visible = false;
                        this.btnUpdate.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            //DataTable dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.PARTS);
            this.grvWH1.DataSource = null;
            this.grvWH1.DataBind();
            this.grvItem.DataSource = null;
            this.grvItem.DataBind();
            this.grvStock.DataSource = null;
            this.grvStock.DataBind();
            this.grvWH.DataSource = null;
            this.grvWH.DataBind();
            LoadDealerStock();
            Timer1.Enabled = false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grvItem, "Select$" + e.Row.RowIndex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtItemCode.Text == "" ||
                      this.txtItemName.Text == "")
                {
                    this.lblError.Text = "Missing Data.";
                    this.lblError.Visible = true;
                    return;
                }
                DataSet dsUpdate = new DataSet();
                DataTable oitm = new DataTable("OITM");
                oitm.Columns.Add("ItemCode");
                oitm.Columns.Add("ItemName");
                oitm.Columns.Add("FrgnName");
                oitm.Columns.Add("ItmsGrpCod");
                oitm.Columns.Add("InvntryUom");
                oitm.Columns.Add("UserText");
                oitm.Columns.Add("NumInSale");
                //UDF
                oitm.Columns.Add("U_DealerID");
                oitm.Columns.Add("U_Model");
                oitm.Columns.Add("U_Seding");
                oitm.Columns.Add("U_Class");
                oitm.Columns.Add("U_NW");
                oitm.Columns.Add("U_NBR");
                oitm.Columns.Add("U_PNC");
                oitm.Columns.Add("U_NewLocation");
                oitm.Columns.Add("U_SubLocation");

                DataRow r = oitm.NewRow();
                r["ItemCode"] = this.txtItemCode.Text;
                r["ItemName"] = this.txtItemName.Text;
                r["FrgnName"] = this.txtForeignName.Text;
                r["ItmsGrpCod"] = "102";
                r["InvntryUom"] = this.txtUnit.Text.Trim();
                r["UserText"] = this.txtRemarks.Text.Trim();
                r["NumInSale"] = this.txtPGK.Text.Trim();
                //UDF
                r["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                r["U_Model"] = this.txtModel.Text.Trim();
                r["U_Seding"] = this.txtSeding.Text.Trim();
                r["U_Class"] = this.txtClass.Text.Trim();
                r["U_NW"] = this.txtNW.Text.Trim();
                r["U_NBR"] = this.txtGroupNBR.Text.Trim();
                r["U_PNC"] = this.txtPartNameCode.Text.Trim();
                r["U_NewLocation"] = this.txtLocation.Text.Trim();
                r["U_SubLocation"] = this.txtSubLocation.Text.Trim();
                oitm.Rows.Add(r);


                DataTable oitw = new DataTable("OITW");
                oitw.Columns.Add("ItemCode");

                r = oitw.NewRow();
                r["ItemCode"] = this.txtItemCode.Text;
                oitw.Rows.Add(r);


                DataTable itm1 = new DataTable("ITM1");
                itm1.Columns.Add("ItemCode");
                itm1.Columns.Add("PriceList");

                r = itm1.NewRow();
                r["PriceList"] = this.dllPriceList.SelectedValue;
                r["ItemCode"] = this.txtItemCode.Text;
                itm1.Rows.Add(r);

                DataTable itm12 = new DataTable("ITM12");
                itm12.Columns.Add("UomEntry");

                r = itm12.NewRow();
                r["UomEntry"] = "-1";
                itm12.Rows.Add(r);

                DataTable itm2 = new DataTable("ITM2");
                itm2.Columns.Add("VendorCode");
                itm2.Columns.Add("ItemCode");
                itm2.Columns.Add("ObjType");
                itm2.Columns.Add("LogInstanc");

                r = itm2.NewRow();
                r["VendorCode"] = this.txtVendorID.Text;
                r["ItemCode"] = this.txtItemCode.Text.Trim();
                r["ObjType"] = 4;
                r["LogInstanc"] = 0;
                itm2.Rows.Add(r);

                DataSet ds = new DataSet();
                ds.Tables.Add(oitm);

                 DataTable tbCheck = CheckItem(this.txtItemCode.Text);
                 if (tbCheck != null && tbCheck.Rows.Count == 0)
                 {
                     this.hdnIsUpdate.Value = "";
                 }
                 else
                 { 
                     this.hdnIsUpdate.Value = "1";
                 }

                 if (this.hdnIsUpdate.Value.Length == 0 )
                 {
                     ds.Tables.Add(oitw);
                     ds.Tables.Add(itm1);
                     ds.Tables.Add(itm12);
                     ds.Tables.Add(itm2);
                 }

                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DocumentXML docXml = new DocumentXML();
                string xml = docXml.ToXMLStringFromDS("4", ds);

                Transaction ts = new Transaction();
                bool isUpdate = false;
                if (this.hdnIsUpdate.Value == "1")
                {
                    isUpdate = true;
                }
                DataSet dsRet = ts.CreateMarketingDocument(xml, "4", this.txtItemCode.Text, isUpdate, dbType);
                if ((int)dsRet.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    this.lblError.Text = GeneralFunctions.UrlFullEncode(dsRet.Tables[0].Rows[0]["ErrMsg"].ToString());
                }
                else
                {
                    this.lblError.Text = "Operation complete sucessful!";
                    this.hdnIsUpdate.Value = "1";
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ResetForm();
            LoadItem();
            MasterData obj = new MasterData();
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            if (dbType == "VSM")
            {
                LoadDealerStock();
            }
            else
            {
                DataTable tbSource = new DataTable();
                tbSource.Columns.Add("VSM Stock");
                tbSource.Columns.Add("VSM Avaiable");
                DataRow rSource = tbSource.NewRow();
                rSource["VSM Avaiable"] = double.Parse(GetAvailableQty(this.txtSpareParts.Text.Trim(), "HCM-PAR", "VSM")) + double.Parse(GetAvailableQty(this.txtSpareParts.Text.Trim(), "HN-PAR", "VSM"));
                rSource["VSM Stock"] = double.Parse(GetStock(this.txtSpareParts.Text, "HCM-PAR", "VSM")) + double.Parse(GetStock(this.txtSpareParts.Text, "HN-PAR", "VSM"));
                tbSource.Rows.Add(rSource);
                this.grvStock.DataSource = tbSource;
                this.grvStock.DataBind();
            }
            DataSet dsOldItemCode = obj.GetOldItemCode(dbType, this.txtSpareParts.Text.Trim());
            if (dsOldItemCode != null)
            {
                this.grvItem.DataSource = dsOldItemCode;
                this.grvItem.DataBind();
            }
            DataSet dsItem = new DataSet();
            if (dbType == "VSM")
            {
                dsItem = obj.GetVSMItemProcessing(dbType, this.txtSpareParts.Text.Trim());
            }
            else
            {
                dsItem = obj.GetDealerItemProcessing(dbType, this.txtSpareParts.Text.Trim());
            }
            if (dsItem != null)
            {
                this.grvWH1.DataSource = dsItem;
                this.grvWH1.DataBind();
            }

            double dsPrice = obj.GetPartsGrossPrice(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), this.txtSpareParts.Text, "1");
            this.txtEPLPrice.Text = GF.FormatNumeric(dsPrice.ToString(), "PriceDec");
        }

        private void LoadDealerStock()
        {
            MasterData obj = new MasterData();
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            DataTable tb1 = new DataTable();
            tb1.Columns.Add("VSM");
            tb1.Columns.Add("HaNoi");
            tb1.Columns.Add("Production");
            DataRow r = tb1.NewRow();
            r["VSM"] = double.Parse(GetStock(this.txtItemCode.Text, "HCM-PAR", dbType)) - double.Parse(GetSO(this.txtSpareParts.Text, "HCM-PAR"));
            r["HaNoi"] = double.Parse(GetStock(this.txtItemCode.Text, "HN-PAR", dbType)) - double.Parse(GetSO(this.txtSpareParts.Text, "HN-PAR"));
            r["Production"] = 0;
            tb1.Rows.Add(r);
            this.grvWH.DataSource = tb1;
            this.grvWH.DataBind();


            DataSet dsCustomer = obj.GetAllCustomers("VSM", this.txtSpareParts.Text);
            if (dsCustomer != null && dsCustomer.Tables.Count > 1)
            {
                DataTable tbCus = dsCustomer.Tables[0];
                DataTable tbWhs = dsCustomer.Tables[1];
                DataTable tbItem = dsCustomer.Tables[2];

                DataTable tbSource = new DataTable();
                tbSource.Columns.Add("Dealer");
                foreach (DataRow row in tbCus.Rows)
                {
                    tbSource.Columns.Add(row["CardCode"].ToString());
                }
                DataRow rSource = tbSource.NewRow();
                rSource["Dealer"] = "Stock";
                foreach (DataRow row in tbCus.Rows)
                {
                    DataRow[] rWh = tbWhs.Select("U_DealerID='" + row["CardCode"].ToString() + "'");
                    if (rWh.Length > 0)
                    {
                        DataRow[] rOnHand = tbItem.Select("WhsCode='" + rWh[0]["WhsCode"].ToString() + "'");
                        if (rOnHand.Length > 0)
                        {
                            if (rOnHand[0]["OnHand"].ToString().Length > 0)
                            {
                                rSource[row["CardCode"].ToString()] = double.Parse(rOnHand[0]["OnHand"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                            }
                            else
                            {
                                rSource[row["CardCode"].ToString()] = 0;
                            }
                        }
                    }
                }
                tbSource.Rows.Add(rSource);
                this.grvStock.DataSource = tbSource;
                this.grvStock.DataBind();
            }
        }
        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<string> GetItems(string prefixText)
        {
            List<string> Items = new List<string>();
            DataTable dt = LoadItemCodes(prefixText);
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Items.Add(dt.Rows[i]["ItemCode"].ToString());
                }
            }
            return Items;
        }
        private static DataTable LoadItemCodes(string itemCode)
        {
            MasterData obj = new MasterData();
            DataSet dsOITM = obj.GetItemsByItemGroupTop("VSM", "VSM", "102" +
                " and ( ItemCode like '%" + itemCode + "%'  )");
            if (dsOITM != null && dsOITM.Tables != null & dsOITM.Tables[0].Rows.Count > 0)
            {
                return dsOITM.Tables[0];
            }
            return null;
        }
        private DataTable CheckItem(string itemCode)
        {
            MasterData obj = new MasterData();
            DataSet dsOITM = obj.GetItemsByItemGroupTop("VSM", "VSM", "102" +
                " and ( ItemCode = '" + itemCode + "'  )");
            return dsOITM.Tables[0];
        }
        private string GetAvailableQty(string ItemCode, string wareHouse,string dbType)
        {
          
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            string lsSqlCommand = "select  (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) )) As Available";
            lsSqlCommand += " From OITW where ItemCode = '" + ItemCode + "' and WhsCode  ='" + wareHouse + "'";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "Available");
        }
        private string GetStock(string ItemCode, string wareHouse, string dbType)
        {
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            string lsSqlCommand = "SELECT ISNULL(SUM(OnHand), 0)  As OnHand";
            lsSqlCommand += " FROM OITW WHERE ItemCode = '" + ItemCode + "' and WhsCode  ='" + wareHouse + "'";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "OnHand");
        }
        private string GetSO(string ItemCode, string wareHouse)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            string lsSqlCommand = "SELECT ISNULL(SUM(Quantity),0)  As Quantity";
            lsSqlCommand += " FROM RDR1 WHERE ItemCode = '" + ItemCode + "' and WhsCode  ='" + wareHouse + "'";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "Quantity");
        }
        private void LoadItem()
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtSpareParts.Text.Trim()))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Pls. input text to filter." + "','');", true);
                    return;
                }
                MasterData obj = new MasterData();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                DataSet dsOITM = obj.GetPartsItemsByItemGroup("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(), "102" +
                    " and ( T0.ItemCode like '%" + this.txtSpareParts.Text.Trim() + "%' Or ItemName like '%" + this.txtSpareParts.Text.Trim() + "%' )");
                if (dsOITM != null && dsOITM.Tables != null & dsOITM.Tables[0].Rows.Count > 0)
                {
                    this.hdnIsUpdate.Value = "1";
                    DataRow r = dsOITM.Tables[0].Rows[0];
                    this.txtItemCode.Text = r["ItemCode"].ToString();
                    this.txtItemName.Text = r["ItemName"].ToString();
                    this.txtForeignName.Text = r["FrgnName"].ToString();
                    this.txtUnit.Text = r["InvntryUom"].ToString();
                    this.txtRemarks.Text = r["UserText"].ToString();
                    this.txtPGK.Text = GF.FormatNumeric(r["NumInSale"].ToString(), "PercentDec");
                    //UDF
                    this.txtModel.Text = r["U_Model"].ToString();
                    this.txtSeding.Text = r["U_Seding"].ToString();
                    this.txtClass.Text = r["U_Class"].ToString();
                    this.txtNW.Text = r["U_NW"].ToString();
                    this.txtGroupNBR.Text = r["U_NBR"].ToString();
                    this.txtPartNameCode.Text = r["U_PNC"].ToString();
                    this.txtLocation.Text = r["U_NewLocation"].ToString();
                    this.txtSubLocation.Text = r["U_SubLocation"].ToString();
                    this.txtVSP.Text = r["U_VSP"].ToString();
                    this.txtUnitPrice.Text = GF.FormatNumeric(r["Price"].ToString(), "PriceDec");
                }
                else
                {
                    this.hdnIsUpdate.Value = "0";
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ResetForm();
        }
        /// <summary>
        /// 
        /// </summary>
        private void ResetForm()
        {
            this.hdnIsUpdate.Value = "1";
            this.txtItemCode.Text =
            this.txtItemName.Text =
            this.txtForeignName.Text =
            this.txtUnit.Text =
            this.txtRemarks.Text =
            this.txtPGK.Text =
            this.txtModel.Text =
            this.txtSeding.Text =
            this.txtClass.Text =
            this.txtNW.Text =
            this.txtGroupNBR.Text =
            this.txtPartNameCode.Text =
            this.txtLocation.Text =
            this.txtSubLocation.Text =
            this.txtVSP.Text =
            this.txtUnitPrice.Text = string.Empty;
            this.grvWH1.DataSource = null;
            this.grvWH1.DataBind();
            this.grvItem.DataSource = null;
            this.grvItem.DataBind();
            this.grvStock.DataSource = null;
            this.grvStock.DataBind();
            this.grvWH.DataSource = null;
            this.grvWH.DataBind();
            LoadDealerStock();
        }
    }
}